export type RedirectTarget = string | { pathname: string; params?: Record<string, string> };

export function encodeRedirectParam(target: RedirectTarget): string {
  return encodeURIComponent(JSON.stringify(target));
}

export function normalizeRedirectParam(
  raw: string | string[] | undefined,
): RedirectTarget | undefined {
  const candidate = Array.isArray(raw) ? raw[0] : raw;

  if (!candidate) {
    return undefined;
  }

  const value = tryDecode(candidate);
  const parsed = tryParseJson(value);

  if (parsed && typeof parsed === 'object' && 'pathname' in parsed) {
    return parsed as RedirectTarget;
  }

  if (value.startsWith('/')) {
    return value;
  }

  return undefined;
}

function tryDecode(value: string) {
  try {
    return decodeURIComponent(value);
  } catch {
    return value;
  }
}

function tryParseJson(value: string) {
  try {
    return JSON.parse(value);
  } catch {
    return null;
  }
}
